package top.linyuxb.lycloud.admin.controller;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import top.linyuxb.lycloud.admin.entity.LyCloudUserEntity;
import top.linyuxb.lycloud.admin.entity.LyConfServerEntity;
import top.linyuxb.lycloud.admin.repository.LyConfServerRepository;
import top.linyuxb.lycloud.admin.service.ILyConfPermissionService;
import top.linyuxb.lycloud.admin.service.ILyConfServerService;
import top.linyuxb.lycloud.admin.service.impl.LoginService;
import top.linyuxb.lycloud.admin.utils.ReturnT;
import top.linyuxb.lycloud.admin.web.annotation.PermissionLimit;

import java.util.*;

import static top.linyuxb.lycloud.admin.web.interceptor.EnvInterceptor.CURRENT_ENV;

/**
 * Created by Intellij IDEA.
 *
 * @Author: linyuxb
 * @Date: 2024/7/29 14:43
 * @Desc: 环境管理
 */
@Controller
@RequestMapping("/server")
public class ServerController {
    @Resource
    private LyConfServerRepository lyConfServerRepository;
    @Resource
    private ILyConfPermissionService lyConfPermissionService;
    @Resource
    private ILyConfServerService lyConfServerService;

    @RequestMapping
    public String index(HttpServletRequest request, Model model) {
        String env = (String) request.getAttribute(CURRENT_ENV);
        LyCloudUserEntity lyCloudUser = (LyCloudUserEntity) request.getAttribute(LoginService.LOGIN_IDENTITY);
        List<LyConfServerEntity> list = lyConfServerRepository.findByEnvOrderByIdDesc(env);
        Set<String> servers = new HashSet<>();
        Boolean status = lyConfPermissionService.getPermissionServers(lyCloudUser, servers);
        list.removeIf(server -> !status && !servers.contains(server.getApp() + "#" + server.getEnv()));
        model.addAttribute("list", list);
        return "server/server.index";
    }

    @ResponseBody
    @RequestMapping("/update")
    @PermissionLimit(adminuser = true)
    public ReturnT<String> update(LyConfServerEntity lyConfServer) {
        if (Objects.isNull(lyConfServer.getId())) {
            return new ReturnT<>(500, "服务id不可为空");
        }
        lyConfServerRepository.editServer(lyConfServer.getId(), lyConfServer.getStatus(), lyConfServer.getWeight());
        lyConfServerRepository.findById(lyConfServer.getId())
                .ifPresent(lyConfServer1 -> lyConfServerService.refreshServer(lyConfServer1));
        return ReturnT.SUCCESS;
    }

}
